<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>上虞区教育体育局疗休养路线调查</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/leancloud-storage@4.13.2/dist/av-min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <style>
        :root {
            --primary: #1a5276;
            --secondary: #3498db;
            --accent: #f39c12;
            --light: #f8f9fa;
            --dark: #2c3e50;
        }
        
        body {
            background: linear-gradient(135deg, #e6f7ff 0%, #f0f8ff 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            padding: 20px 0 50px;
        }
        
        .header {
            background: linear-gradient(to right, var(--primary), var(--secondary));
            color: white;
            border-radius: 15px;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
            padding: 25px 0;
            position: relative;
            overflow: hidden;
        }
        
        .header::before {
            content: "";
            position: absolute;
            top: -50px;
            left: -50px;
            width: 150px;
            height: 150px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
        }
        
        .header::after {
            content: "";
            position: absolute;
            bottom: -30px;
            right: -30px;
            width: 100px;
            height: 100px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
        }
        
        .card {
            border-radius: 15px;
            border: none;
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.05);
            transition: transform 0.3s, box-shadow 0.3s;
            margin-bottom: 25px;
            overflow: hidden;
        }
        
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 20px rgba(0, 0, 0, 0.1);
        }
        
        .card-header {
            background: linear-gradient(to right, var(--secondary), var(--primary));
            color: white;
            font-weight: 600;
            padding: 15px 20px;
            border-radius: 15px 15px 0 0 !important;
        }
        
        .form-control, .form-select {
            border-radius: 10px;
            padding: 12px 15px;
            border: 1px solid #dee2e6;
            transition: all 0.3s;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--secondary);
            box-shadow: 0 0 0 0.25rem rgba(52, 152, 219, 0.25);
        }
        
        .btn-primary {
            background: linear-gradient(to right, var(--primary), var(--secondary));
            border: none;
            border-radius: 10px;
            padding: 12px 30px;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-primary:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(26, 82, 118, 0.4);
        }
        
        .btn-export {
            background: linear-gradient(to right, #27ae60, #2ecc71);
            border: none;
            border-radius: 10px;
            padding: 12px 30px;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-export:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(39, 174, 96, 0.4);
        }
        
        .option-card {
            cursor: pointer;
            transition: all 0.3s;
            border-left: 4px solid transparent;
        }
        
        .option-card:hover {
            background-color: rgba(52, 152, 219, 0.05);
            border-left: 4px solid var(--secondary);
        }
        
        .option-card.selected {
            background-color: rgba(52, 152, 219, 0.1);
            border-left: 4px solid var(--primary);
        }
        
        .count-badge {
            background: var(--accent);
            color: var(--dark);
            font-weight: bold;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 14px;
        }
        
        .footer {
            background: var(--dark);
            color: white;
            padding: 20px 0;
            margin-top: 40px;
            border-radius: 15px 15px 0 0;
            font-size: 14px;
        }
        
        .password-modal .modal-content {
            border-radius: 15px;
            overflow: hidden;
        }
        
        .password-modal .modal-header {
            background: linear-gradient(to right, var(--primary), var(--secondary));
            color: white;
        }
        
        .password-input {
            position: relative;
        }
        
        .password-input i {
            position: absolute;
            right: 15px;
            top: 12px;
            color: #6c757d;
            cursor: pointer;
        }
        
        .required::after {
            content: " *";
            color: #e74c3c;
        }
        
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        @media (max-width: 768px) {
            .card {
                margin-bottom: 15px;
            }
            
            .header h1 {
                font-size: 1.8rem;
            }
            
            .btn {
                width: 100%;
                margin-bottom: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 标题区域 -->
        <div class="header text-center mb-5">
            <h1><i class="fas fa-route me-3"></i>上虞区教育体育局疗休养路线调查</h1>
            <p class="mb-0">请填写您的个人信息并选择疗休养路线</p>
        </div>
        
        <!-- 主表单区域 -->
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="card mb-4">
                    <div class="card-header">
                        <i class="fas fa-user-circle me-2"></i>个人信息
                    </div>
                    <div class="card-body">
                        <form id="surveyForm">
                            <div class="mb-4">
                                <label for="name" class="form-label fw-bold required">姓名</label>
                                <input type="text" class="form-control" id="name" placeholder="请输入您的姓名" required>
                            </div>
                            
                            <div class="mb-4">
                                <label for="idNumber" class="form-label fw-bold required">身份证号码</label>
                                <input type="text" class="form-control" id="idNumber" placeholder="请输入您的身份证号码" required>
                                <div class="form-text">我们将根据身份证号码识别唯一用户</div>
                            </div>
                            
                            <div class="mb-4">
                                <label for="remark" class="form-label fw-bold">备注（携带家属情况）</label>
                                <input type="text" class="form-control" id="remark" placeholder="例如：携带家属2人">
                                <div class="form-text">非必填项，请填写携带家属的数量和情况说明</div>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- 路线选择区域 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <i class="fas fa-map-marked-alt me-2"></i>疗休养路线选择
                    </div>
                    <div class="card-body">
                        <div class="mb-3 fw-bold required">请选择一条疗休养路线：</div>
                        <div id="routeOptions">
                            <!-- 路线选项将通过JS动态生成 -->
                        </div>
                    </div>
                </div>
                
                <!-- 按钮区域 -->
                <div class="d-grid gap-3 d-md-flex justify-content-md-center mt-4">
                    <button type="button" class="btn btn-primary btn-lg" id="submitBtn">
                        <i class="fas fa-paper-plane me-2"></i>提交调查
                    </button>
                    <button type="button" class="btn btn-export btn-lg" id="exportBtn">
                        <i class="fas fa-file-excel me-2"></i>导出数据
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 页脚 -->
        <div class="footer text-center mt-5">
            <div class="container">
                <p class="mb-0">上虞区教育体育局 &copy; 2023 疗休养路线调查系统</p>
                <p class="mb-0">技术支持：教育体育局信息中心</p>
            </div>
        </div>
    </div>
    
    <!-- 密码输入模态框 -->
    <div class="modal fade password-modal" id="passwordModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-lock me-2"></i>导出数据验证</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="passwordInput" class="form-label">请输入导出密码</label>
                        <div class="password-input">
                            <input type="password" class="form-control" id="passwordInput" placeholder="请输入密码">
                            <i class="fas fa-eye" id="togglePassword"></i>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmExport">
                        <span id="exportSpinner" class="d-none loading"></span>
                        <span>导出数据</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 成功提示模态框 -->
    <div class="modal fade" id="successModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body text-center p-5">
                    <div class="mb-4">
                        <i class="fas fa-check-circle text-success" style="font-size: 5rem;"></i>
                    </div>
                    <h3 class="mb-3">提交成功！</h3>
                    <p>感谢您参与疗休养路线调查</p>
                    <button type="button" class="btn btn-primary mt-3" data-bs-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 错误提示模态框 -->
    <div class="modal fade" id="errorModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body text-center p-5">
                    <div class="mb-4">
                        <i class="fas fa-exclamation-circle text-danger" style="font-size: 5rem;"></i>
                    </div>
                    <h3 class="mb-3" id="errorTitle">操作失败</h3>
                    <p id="errorMessage">系统出现错误，请稍后再试</p>
                    <button type="button" class="btn btn-primary mt-3" data-bs-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 引入Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // 初始化LeanCloud - 请替换为您的应用信息
        const APP_ID = 'ZHlxemy1UQK1T2bkoMp9WfRR-gzGzoHsz';
        const APP_KEY = 'y3xskBpRqOkT6564Jf3VrQSp';
        const SERVER_URL = 'https://zhlxemy1.lc-cn-n1-shared.com';
        
        AV.init({
            appId: APP_ID,
            appKey: APP_KEY,
            serverURLs: SERVER_URL
        });
        
        // 路线数据
        const routes = [
            { id: 1, name: "成都乐山五日游", date: "10月27日", price: "5500元/人" },
            { id: 2, name: "福州平潭五日游", date: "9月22日", price: "3000元/人" },
            { id: 3, name: "江西上饶五日游", date: "10月13日", price: "3000元/人" },
            { id: 4, name: "青海敦煌七日游", date: "9月22日", price: "7000元/人" },
            { id: 5, name: "台州神仙居五日游", date: "9月22日", price: "3000元/人" },
            { id: 6, name: "温州南麂岛五日游", date: "9月22日", price: "3000元/人" },
            { id: 7, name: "嘉兴南湖五日游", date: "10月27日", price: "3000元/人" },
            { id: 8, name: "千岛湖五日游", date: "10月13日", price: "3000元/人" },
            { id: 9, name: "岭南上浦", date: "9月22日", price: "3000元/人" },
            { id: 10, name: "曹娥丁宅", date: "10月13日", price: "3000元/人" }
        ];
        
        // 全局变量
        let selectedRouteId = null;
        let routeCounts = {};

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 生成路线选项
            renderRouteOptions();
            
            // 初始化事件监听
            document.getElementById('submitBtn').addEventListener('click', submitSurvey);
            document.getElementById('exportBtn').addEventListener('click', showPasswordModal);
            document.getElementById('confirmExport').addEventListener('click', exportData);
            document.getElementById('togglePassword').addEventListener('click', togglePasswordVisibility);
            
            // 加载路线选择统计数据
            loadRouteCounts();
        });

        // 渲染路线选项
        function renderRouteOptions() {
            const container = document.getElementById('routeOptions');
            container.innerHTML = '';
            
            routes.forEach(route => {
                const count = routeCounts[route.id] || 0;
                
                const optionElement = document.createElement('div');
                optionElement.className = 'card option-card mb-3';
                optionElement.innerHTML = `
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="route" 
                                       id="route${route.id}" value="${route.id}">
                                <label class="form-check-label fw-bold" for="route${route.id}">
                                    （${route.id}）${route.name}-${route.date}【${route.price}】
                                </label>
                            </div>
                            <span class="count-badge">${count}人选择</span>
                        </div>
                    </div>
                `;
                container.appendChild(optionElement);
                
                // 添加选择事件
                optionElement.querySelector('input').addEventListener('change', function() {
                    document.querySelectorAll('.option-card').forEach(card => {
                        card.classList.remove('selected');
                    });
                    if (this.checked) {
                        optionElement.classList.add('selected');
                        selectedRouteId = route.id;
                    }
                });
            });
        }

        // 加载路线选择统计数据
        async function loadRouteCounts() {
            try {
                const SurveyData = AV.Object.extend('SurveyData');
                const query = new AV.Query(SurveyData);
                
                // 分组统计
                const pipeline = {
                    group: {
                        objectId: { routeId: "$routeId" },
                        count: { $sum: 1 }
                    }
                };
                
                const result = await query.aggregate(pipeline);
                
                // 重置计数
                routeCounts = {};
                routes.forEach(route => {
                    routeCounts[route.id] = 0;
                });
                
                // 更新计数
                result.forEach(item => {
                    const routeId = item.objectId.routeId;
                    routeCounts[routeId] = item.count;
                });
                
                // 重新渲染选项
                renderRouteOptions();
            } catch (error) {
                console.error('加载数据统计失败:', error);
            }
        }

        // 提交调查
        async function submitSurvey() {
            const name = document.getElementById('name').value.trim();
            const idNumber = document.getElementById('idNumber').value.trim();
            const remark = document.getElementById('remark').value.trim();
            
            // 验证表单
            if (!name) {
                showError('请输入姓名');
                return;
            }
            
            if (!idNumber || !/^\d{17}[\dXx]$/.test(idNumber)) {
                showError('请输入有效的身份证号码');
                return;
            }
            
            if (!selectedRouteId) {
                showError('请选择一条疗休养路线');
                return;
            }
            
            // 获取选择的路线
            const selectedRoute = routes.find(r => r.id === selectedRouteId);
            const routeName = `（${selectedRoute.id}）${selectedRoute.name}-${selectedRoute.date}【${selectedRoute.price}】`;
            
            try {
                // 检查是否已存在相同身份证的记录
                const SurveyData = AV.Object.extend('SurveyData');
                const query = new AV.Query(SurveyData);
                query.equalTo('idNumber', idNumber);
                const existingRecord = await query.first();
                
                // 创建或更新记录
                let surveyRecord;
                if (existingRecord) {
                    // 更新现有记录
                    surveyRecord = existingRecord;
                } else {
                    // 创建新记录
                    surveyRecord = new SurveyData();
                }
                
                // 设置记录值
                surveyRecord.set('name', name);
                surveyRecord.set('idNumber', idNumber);
                surveyRecord.set('routeId', selectedRouteId);
                surveyRecord.set('routeName', routeName);
                surveyRecord.set('remark', remark);
                surveyRecord.set('submitTime', new Date());
                
                // 保存到LeanCloud
                await surveyRecord.save();
                
                // 更新本地计数
                if (!existingRecord) {
                    routeCounts[selectedRouteId] = (routeCounts[selectedRouteId] || 0) + 1;
                }
                
                // 重新渲染选项以更新计数
                renderRouteOptions();
                
                // 显示成功提示
                const successModal = new bootstrap.Modal(document.getElementById('successModal'));
                successModal.show();
                
                // 重置表单
                document.getElementById('surveyForm').reset();
                document.querySelectorAll('.option-card').forEach(card => {
                    card.classList.remove('selected');
                });
                selectedRouteId = null;
            } catch (error) {
                console.error('提交失败:', error);
                showError('提交失败，请稍后再试');
            }
        }

        // 显示密码输入模态框
        function showPasswordModal() {
            document.getElementById('passwordInput').value = '';
            const passwordModal = new bootstrap.Modal(document.getElementById('passwordModal'));
            passwordModal.show();
        }

        // 切换密码可见性
        function togglePasswordVisibility() {
            const passwordInput = document.getElementById('passwordInput');
            const icon = document.getElementById('togglePassword');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                passwordInput.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }

        // 导出数据
        async function exportData() {
            const password = document.getElementById('passwordInput').value;
            
            if (password !== 'jtj123') {
                showError('密码错误，请重新输入');
                return;
            }
            
            // 显示加载状态
            const exportBtn = document.getElementById('confirmExport');
            const exportSpinner = document.getElementById('exportSpinner');
            exportSpinner.classList.remove('d-none');
            exportBtn.disabled = true;
            
            try {
                // 从LeanCloud获取所有数据
                const SurveyData = AV.Object.extend('SurveyData');
                const query = new AV.Query(SurveyData);
                query.addDescending('submitTime');
                const results = await query.find();
                
                // 准备Excel数据
                const data = results.map(item => {
                    return {
                        '姓名': item.get('name'),
                        '身份证号码': item.get('idNumber'),
                        '选择路线': item.get('routeName'),
                        '备注': item.get('remark') || '',
                        '提交时间': formatDate(item.get('submitTime'))
                    };
                });
                
                // 创建工作簿
                const ws = XLSX.utils.json_to_sheet(data);
                const wb = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(wb, ws, "调查数据");
                
                // 导出Excel
                XLSX.writeFile(wb, '疗休养路线调查数据.xlsx');
                
                // 关闭模态框
                const passwordModal = bootstrap.Modal.getInstance(document.getElementById('passwordModal'));
                passwordModal.hide();
            } catch (error) {
                console.error('导出失败:', error);
                showError('导出数据失败，请稍后再试');
            } finally {
                // 重置按钮状态
                exportSpinner.classList.add('d-none');
                exportBtn.disabled = false;
            }
        }

        // 显示错误消息
        function showError(message, title = '操作失败') {
            document.getElementById('errorTitle').textContent = title;
            document.getElementById('errorMessage').textContent = message;
            const errorModal = new bootstrap.Modal(document.getElementById('errorModal'));
            errorModal.show();
        }

        // 格式化日期
        function formatDate(date) {
            const d = new Date(date);
            return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
        }
    </script>
</body>
</html>